package com.zyf.channe.writer

import com.android.build.api.artifact.SingleArtifact
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.Directory
import org.gradle.api.provider.Provider
import java.io.File

class ChannelWriterPlugin : Plugin<Project> {
    private var apkPath: Provider<Directory>?= null
    override fun apply(project: Project) {
        val extension = project.extensions.create<ChannelPluginExtension>("channelConfig", ChannelPluginExtension::class.java)
        val androidComponents = project.extensions.getByType(ApplicationAndroidComponentsExtension::class.java)


        androidComponents.onVariants { variant ->
            if (variant.buildType == "release") {
                val apkProvider = variant.artifacts.get(SingleArtifact.APK)
                apkPath = apkProvider
            }
        }
        val printApkPaths = project.tasks.register("channelWriter") {
            it.doLast {
                println("apkPath>>${apkPath?.orNull?.asFile?.absolutePath}")
                apkPath?.orNull?.asFile?.run {
                    println("apkPath>>${absolutePath}")
                    if (isDirectory){
                        for (file in listFiles()){
                            if (file.extension == "apk"){
                                //读取apk配置
                                val channelDir = project.layout.buildDirectory.dir("outputs").get().dir("channelApk").asFile
                                if (!channelDir.exists()) {
                                    channelDir.mkdirs()
                                }
                                if (file.exists()){
                                    deleteFile(channelDir)//清空文件夹
                                    val channelFile = File(extension.channelFilePath)
                                    println("${extension.channelFilePath}")
                                    if (channelFile.exists()){
                                        readChannel(channelFile,file,extension,channelDir)
                                        println("自定义配置channel")
                                    }else{
                                        val defFile = project.layout.projectDirectory.file("channel.txt").asFile
                                        if (defFile.exists()) {
                                            readChannel(defFile,file,extension,channelDir)
                                            println("默认配置channel")
                                        }else{
                                            println("渠道配置文件不存在，请在app目录下创建channel文件或者配置channel文件路径")
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
        project.tasks.whenTaskAdded { task ->
            if (task.name == "assembleRelease") {
                task.finalizedBy(printApkPaths)
            }
        }
    }
    private fun readChannel(channelFile: File,inputApk: File ,extension: ChannelPluginExtension,channelDir: File){
        var outputDir = File(extension.outApkPath)
        if (extension.outApkPath==""){
            outputDir = File(channelDir,"signApk")
        }
        if (!outputDir.exists()){
            outputDir.mkdirs()
        }
        val channels = channelFile.readLines().map { it.trim() }.filter { it.isNotEmpty() }
        for (key in channels) {
            val destApk = File(outputDir, "${inputApk.nameWithoutExtension}-${key}.apk")
            inputApk.copyTo(destApk, overwrite = true)
            ChannelWriter.put(destApk, key)
            println("渠道包路径>>: ${destApk.absolutePath}")
        }
    }
    private fun deleteFile(dir: File){
        println("开始删除旧文件")
        if (dir.exists() && dir.isDirectory) {
            // 获取目录下的所有文件和子目录，并逐个删除
            dir.listFiles()?.forEach { file ->

                val state= file.deleteRecursively()
                println("删除>>${file.name}>>${if (state) "成功" else "失败"}")
            }
        }
        println("删除旧文件完成")
    }

}